<template>
  <el-dialog :title="title" :visible.sync="visible" width="600px" :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">

      <el-form-item label="文件：" prop="name">
        <el-upload class="upload-demo" :action="fileAction" :headers="fileHeaders" :limit="1" :file-list="fileList"
          :before-upload="beforeFileUpload" :on-success="handleFileSuccess" :on-remove="handleRemove">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传word、excel、ppt、pdf、txt、图片、视频、压缩包，且不超过150MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="资料类型：" prop="materialCategoryType">
        <el-select v-model="ruleForm.materialCategoryType" placeholder="请选择" class="input-w300" clearable filterable>
          <el-option v-for="dict in dict.type.sys_material_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="简介：" prop="materialDesc">
        <el-input v-model.trim="ruleForm.materialDesc" type="textarea" placeholder="请输入" clearable class="input-w300"
          maxlength="200" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addMaterial, updateMaterial } from "@/api/file";
import { getToken } from "@/utils/auth";

export default {
  components: {},
  dicts: ['sys_material_type', 'sys_position_type'],
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    title: {
      default: '',
      type: String
    },
    editType: {
      default: 'add',
      type: String
    },
    editData: {
      default: {},
      type: Object
    },
    materialCategoryType: {
      default: '',
      type: String
    }
  },
  data () {
    return {
      fileAction: process.env.VUE_APP_BASE_API + '/common/upload',
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      ruleForm: {
        materialCategoryType: '',
        materialDesc: "",
        materialName: "",
        materialType: '',
        uploadUrl: "",
        sourceId: this.$store.state.user.userInfo.deptId
      },
      rules: {
        picUrl: [
          { required: true, message: '请上传文件', trigger: 'blur' },
        ],
      }
    };
  },
  watch: {
    visible (val) {
      if (val) {
        if (this.editType === 'edit') {
          this.ruleForm = JSON.parse(JSON.stringify(this.editData))
          if (this.ruleForm.materialName && this.ruleForm.uploadUrl) {
            this.fileList = [
              { name: this.ruleForm.materialName, url: this.ruleForm.uploadUrl }
            ]
          }
          this.ruleForm.materialCategoryType=JSON.stringify(this.ruleForm.materialCategoryType)
        } else {
          this.ruleForm.materialCategoryType = this.materialCategoryType
        }
      } else {
        this.ruleForm = {
          materialDesc: "",
          materialName: "",
          materialType: '',
          uploadUrl: "",
          sourceId: this.$store.state.user.userInfo.deptId
        }
        this.fileList = []
        this.resetForm('ruleForm')
      }
    }
  },
  methods: {
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    // 确定
    handleConfirm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await (this.ruleForm.id ? updateMaterial(this.ruleForm) : addMaterial(this.ruleForm))
          if (res.code === 200) {
            this.$message.success('保存成功');
            this.handleClose()
          }
        }
      });
    },
    // 文件上传前检查
    beforeFileUpload (file) {
      var FileExt = file.name.replace(/.+\./, "");
      const isLtM = file.size / 1024 / 1024 < 150;

      const fileTypeList = [
        // 图片
        "bmp", "gif", "jpg", "jpeg", "png",
        // word excel powerpoint
        "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
        // 压缩文件
        "rar", "zip", "gz", "bz2",
        // 视频格式
        "avi", "wmv", "mpg", "mpeg", "mov", "rm", "ram", "swf", "flv", "mp4", "wma", "rm", "rmvb", "flv", "mpg", "mkv",
        // pdf
        "pdf"]
      let isFileType = fileTypeList.indexOf(FileExt.toLowerCase()) > -1
      if (!isFileType || !isLtM) {
        this.$message.error('请检查文件格式以及大小');
      }
      return isFileType && isLtM;
    },
    // 文件上传成功
    handleFileSuccess (res, file) {
      if (res.code === 200) {
        let fileName = res.originalFilename || ''
        let fileType = fileName.substring(fileName.lastIndexOf(".") + 1) || ''
        this.ruleForm.materialName = fileName

        this.ruleForm.uploadUrl = res.fileName || ''

        let type = {
          0: ['doc', 'docx'],
          1: ['xlsx', 'xls'],
          2: ['pptx', 'ppt'],
          3: ["bmp", "gif", "jpg", "jpeg", "png"],
          4: ['pdf'],
          5: ['zip', 'rar', 'gz', 'bz2'],
          6: ["avi", "wmv", "mpg", "mpeg", "mov", "rm", "ram", "swf", "flv", "mp4", "wma", "rm", "rmvb", "flv", "mpg", "mkv"]
        }

        for (let item in type) {
          if (type[item].indexOf(fileType.toLowerCase()) > -1) {
            this.ruleForm.materialType = item
          }
        }
      }
    },
    // 文件删除
    handleRemove (file, fileList) {
      this.ruleForm.materialName = ''
    },
    // 取消
    handleCancel () {
      this.$emit('update:visible', false)
    },
    // 关闭
    handleClose () {
      this.$emit('update:visible', false)
      this.$emit('close')
    }
  }
};
</script>
<style lang='scss' scoped></style>
